package com.kcsj.dao;
//201902104058胡庆阳


import com.kcsj.util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * @author 胡庆阳
 * 29th Nov. 2020
 */
public final class TotalNumberDao {
    private static TotalNumberDao totalNumberDao = new TotalNumberDao();

    private TotalNumberDao() {
    }

    public static TotalNumberDao getInstance() {
        return totalNumberDao;
    }


    /**
     * 返回指定表的元素数量
     * @param connection
     * @param tableName 表名
     * @return 元组数量
     * @throws SQLException
     */
    public int count(Connection connection,String columnName, String tableName,String condition) throws SQLException {
        String sql_count = "SELECT COUNT(?) as number FROM " + tableName +" WHERE "+condition+" = ?";

        PreparedStatement pstmt_count =
                connection.prepareStatement(sql_count);
        pstmt_count.setString(1,columnName);
        pstmt_count.setString(2,condition);
        ResultSet resultSet_count = pstmt_count.executeQuery();
        int counter = 0;
        if (resultSet_count.next()) {
            counter = resultSet_count.getInt("number");
        }
        JdbcHelper.close(pstmt_count);
        return counter;
    }
}
